// 线上环境 
export const indexUrl = 'https://www.lpmyblog.cn/applet';
export const imageUrl = 'https://www.lpmyblog.cn';
export const uploadImage = 'https://www.lpmyblog.cn/'
export const upImage = 'https://www.lpmyblog.cn/'

// // 线下内网环境
// export const indexUrl = 'http://192.168.1.76:8080/applet';
// export const imageUrl = 'http://192.168.1.76:8080';
// export const uploadImage = 'http://192.168.1.76:8080/'
// export const upImage = 'http://192.168.1.76:8080/'

// 获取用户token
const getUserToken = () => {
	const userInfo = uni.getStorageSync('userInfo');
	return userInfo ? userInfo.token : null;
};

// 清空本地存储
const clearLocalStorage = () => {
	uni.removeStorageSync('userInfo');
};
// 上传文件封装
export const uploadFile = {
	/**
	 * 上传文件
	 * @param {string} filePath - 文件路径（通过 uni.chooseImage 或 uni.chooseFile 获取）
	 * @returns {Promise} - 返回上传结果
	 */
	async upload(filePath) {
		const userToken = getUserToken();
		console.log('Token:', userToken);
		console.log('文件上传:', filePath);

		try {
			const response = await uni.uploadFile({
				url: `${indexUrl}/upload`, // 拼接完整 URL
				filePath: filePath, // 文件路径
				name: 'file', // 后端接收文件的字段名
				header: {
					'Content-Type': 'multipart/form-data', // 设置正确的 Content-Type
					Authorization: userToken ? userToken : '', // 传递 token
				},
			});

			console.log('上传响应:', response);
			console.log('响应内容:', response.data);

			// 解析响应数据
			if (response.statusCode === 200) {
				const resData = JSON.parse(response.data); // 将响应数据解析为 JSON
				return resData;
			} else {
				throw new Error(`上传失败，状态码：${response.statusCode}`);
			}
		} catch (error) {
			console.error('上传失败:', error);
			throw error; // 抛出错误
		}
	},
};
// 封装请求函数
const makeRequest = async (method, url, data = {}, header = {}) => {
	const userToken = getUserToken();
	console.log('ken', userToken);
	// const userToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjozLCJpc3MiOiJBdXRob3JpemF0aW9uIiwiZXhwIjoxODYzNzQzMjM1fQ.dUyzplSymB93HlZX3C2H-Cotbrh0';
	try {
		const res = await new Promise((resolve, reject) => {
			uni.request({
				url: `${indexUrl}${url}`,
				method,
				data,
				header: {
					'Content-Type': 'application/json',
					Authorization: userToken ? userToken : '',
					...header,
				},
				success: (response) => {
					console.log('查看网络放飞状态', response);
					if (response.statusCode == 200) {
						if (response.data.code == 310) {
							clearLocalStorage();
							uni.showToast({
								title: '登录已过期，请重新登录',
								icon: 'none',
							});
						}
						resolve(response.data);
					} else {
						reject(response);
					}
				},
				fail: (err) => reject(err),
			});
		});
		return res;
	} catch (err) {
		throw err;
	}
};

// 重构的 API 请求封装
export const request = {
	get(url, params = {}, header = {}) {
		return makeRequest('GET', url, params, header);
	},

	post(url, data = {}, header = {}) {
		return makeRequest('POST', url, data, header);
	},

	put(url, data = {}, header = {}) {
		return makeRequest('PUT', url, data, header);
	},

	delete(url, data = {}, header = {}) {
		return makeRequest('DELETE', url, data, header);
	},
};

export default request;